package com.gitee.fastmybatis.spring.boot.autoconfigure.multi;

import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Arrays;

/**
 * 多数据源条件判断
 *
 * @author thc
 */
public class MultiDatasourceCondition implements ConfigurationCondition {

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        Environment environment = conditionContext.getEnvironment();
        if (environment instanceof ConfigurableEnvironment) {
            ConfigurableEnvironment standardEnvironment = (StandardEnvironment) environment;
            final MutablePropertySources sources = standardEnvironment.getPropertySources();
            return sources.stream()
                    .filter(ps -> ps instanceof EnumerablePropertySource)
                    .map(ps -> ((EnumerablePropertySource<?>) ps).getPropertyNames())
                    .flatMap(Arrays::stream)
                    .anyMatch(data -> data.startsWith(MultiDataSourceProps.SPRING_MULTI_DATASOURCE));
        }
        return false;
    }

}
